package com.training.spring.controller;

import com.training.spring.model.Person;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;


// @RestController = @Controller + @ResponseBody
// @Controller: 类似一个服务员,既能端菜(返回数据),又能递菜单(返回页面)
// 但默认情况下,服务员认为你递出的是"视图路径",如果需要它直接返回数据,需要加上"@ResponseBody"标签.
// @RestController: 一个"专门端菜"的服务员,默认自带"@ResponseBody"标签,永远直接找数据,不找"试图路径"
// @ResponseBody: 一个标签,贴在类或方法上,代表"直接返回数据,不要找视图".
@RequestMapping("return")
//@RestController
@Controller
public class ReturnController {
    // 匹配static/index.html
    // "/index.html"为绝对路径,直接匹配"/index.html"
    @RequestMapping("returnPage1")
    public String returnPage1(){
        return "/index.html";
    }
    // 匹配static/return/index.html
    // "index.html"为相对路径,匹配的位置为"return/index.html"
    @RequestMapping("returnPage2")
    public String returnPag2(){
        return "index.html";
    }
    // 必须加上"ResponseBody"以返回数据
    // ContentType为"text/html"
    @ResponseBody
    @RequestMapping("/returnHTML")
    public String returnHTML(){
        return "<h1>HTML</h1>";
    }
    // 自动识别并规范某些信息,如"返回Person类,自动优化成JSON代码"
    // ContentType为"application/json"
    @ResponseBody
    @RequestMapping("/returnJSON")
    public Person returnJSON(){
        Person person = new Person();
        person.setName("zhangsan");
        person.setAge(15);
        person.setPassword("123456");
        return person;
    }
    // 想要取消自动识别信息格式,可以我们自己来设置一个信息格式
    // 此处直接返回字符串"<h1>HTML</h1>".
    @ResponseBody
    @RequestMapping("/setContentType")
    public void setContentType(HttpServletResponse response) throws IOException {
        response.setContentType("text/plain");// 纯文本
        response.getOutputStream().write("<h1>HTML</h1>".getBytes(StandardCharsets.UTF_8));
    }
    // 手动设定ContentType
    @ResponseBody
    @RequestMapping(value = "/setContentType2",produces = "text/plain")
    public String setContentType2(HttpServletResponse response){
        return "<h1>hello world!</h1>";
    }
    @ResponseBody
    @RequestMapping(value = "/setContentType3",produces = "application/json")
    public String setContentType3(){
        return "{\"OK\":1}";
    }
    // 自动设置返回的状态码,某些如"特定状态码,显示某页面"的情境下应用
    @ResponseBody
    @RequestMapping("/setStatus")
    public String setStatus(HttpServletResponse response){
        response.setStatus(502);
        return "设置状态码成功";
    }
    @ResponseBody
    @RequestMapping("/setHeader")
    public String setHeader(HttpServletResponse response){
        response.setHeader("My-Header","MyHeader");
        return "Header设置成功";
    }
}